$(document).ready(function()
{
    var markersmap = [];
    var htmlsmap   = [];
    var churchinfo = [];
    var pastorinfo = [];
    var churchmap  = null;
    var infowindow;

    var url = location.href;
    
    var baseURL = url.substring(0, url.indexOf('/', 14));
    var directory = "";
    
    if (baseURL == 'http://localhost' || baseURL == 'http://3kdigitaldesigns.com')
    {
        directory = '/evd';
    }
        
    // initialize map
    var mapObjmap = document.getElementById("map");
    if (mapObjmap != 'undefined' && mapObjmap != null)
    {
    
        infowindow = new google.maps.InfoWindow();
        
        google.maps.event.addListener(infowindow, 'closeclick', function() {
    
            churchmap.setZoom(8);
            infowindow.setContent('');
            resetSelectedMarkers();
        });

        var mapOptionsmap = {
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR},
            zoomControlOptions: {style: google.maps.ZoomControlStyle.LARGE}
        };
        
        mapOptionsmap.center = new google.maps.LatLng(10.343100, 123.961000);
                
        churchmap = new google.maps.Map(mapObjmap,mapOptionsmap);
    }
    
    function resetSelectedMarkers()
    {
        for (i = 0; i < markersmap.length; i++)
        {
            markersmap[i].setIcon(new google.maps.MarkerImage(baseURL + directory + "/themes/images/map/selected.png"));
        }
    }
    
    function scrollToMarker(index)
    {
        resetSelectedMarkers();
        
        churchmap.setZoom(16);
        churchmap.panTo(markersmap[index].getPosition());
        
        markersmap[index].setIcon(new google.maps.MarkerImage(baseURL + directory + "/themes/images/map/highlighted.png"));
        
        infowindow.setContent(htmlsmap[index]);
        infowindow.open(churchmap,markersmap[index]);
    }
    
    function createMarker(map, point, title, html, sidebar_id, openers)
    {
        var marker_options = {
            position: point,
            map: map,
            title: title,
            icon: baseURL + directory + '/themes/images/map/selected.png'
        };
        
        //create marker
        var new_marker = new google.maps.Marker(marker_options);
        
        google.maps.event.addListener(new_marker, 'click', function()
        {
            resetSelectedMarkers();
            
            if (map.getZoom() < 16)
            {
                map.setZoom(16);
            }
            
            map.panTo(new_marker.getPosition())
            
            new_marker.setIcon(new google.maps.MarkerImage(baseURL + directory + "/themes/images/map/highlighted.png"));
            
            infowindow.setContent(html);
            infowindow.open(map,new_marker);
            
            
        });
        
        google.maps.event.addListener(new_marker, 'mouseover', function()
        {
            var icon = new google.maps.MarkerImage(baseURL + directory + "/themes/images/map/highlighted.png");
            new_marker.setIcon(icon);
        });
        
        google.maps.event.addListener(new_marker, 'mouseout', function()
        {
            if (html!= infowindow.getContent())
            {
                var icon = new google.maps.MarkerImage(baseURL + directory + "/themes/images/map/selected.png");
                new_marker.setIcon(icon);
            }
        });
    
        return new_marker;
    }

    function isArray(a) {return isObject(a) && a.constructor == Array;}
    function isObject(a) {return (a && typeof a == 'object') || isFunction(a);}
    function isFunction(a) {return typeof a == 'function';}
    function isEmpty(obj) { for(var i in obj) { return false; } return true; }
    
    function updateCityValues()
    {
        $.facebox('Loading contents');
        
        var url = baseURL + directory + '/church-locator/update-cities';
        
        var values = {
            state_id : $("#province").val()
        };
        
        $.ajax(
        {
            type: "POST",
            url: url,
            data: values,
            success: function (data)
            {
                var value = jQuery.parseJSON(data);
                
                if (value.length > 1 )
                {
                    var coods = value[0].split(",");
                    var point = new google.maps.LatLng(coods[0], coods[1]);
                    
                    churchmap.panTo(point);
                }
                
                if (churchmap.getZoom() > 8)
                {
                    churchmap.setZoom(8);
                }
                                
                // disable the city select before updating its values
                $("#city").attr('disabled', 'disabled');
                
                $("#city").html("");
                $("#city").append('<option value="0" selected>Select a City</option>');
                
                for ( i = 1; i < value.length; i++ )
                {
                    $("#city").append('<option value="' + value[i].id + '">' + value[i].name +'</option>');
                }
                
                // re-enable it by removing the disabled attribute
                $("#city").removeAttr('disabled');
            }
        });
        
        // reset the value of city to 0.
        $("#city").val(0);
        
        updateSearchResult();
    }
    
    function getSocialInfo(social_id, social_link)
    {
        var toreturn = [];
        
        switch (social_id)
        {
            case '1':
                type = 'youtube';
                altt = social_link + ' at YouTube.com';
                link = 'http://youtube.com/user/' + social_link;
                break;
            case '2':
                type = 'facebook';
                altt = 'Visit us on Facebook.com';
                link = 'http://facebook.com/' + social_link;
                break;
            case '3':
                type = 'twitter';
                altt = social_link +' at Twitter.com';
                link = 'http://twitter.com/' + social_link;
                break;
            case '4':
                type = 'ustream';
                altt = 'Stream with us at UStream.tv';
                link = 'http://ustream.tv/channel/' + social_link;
                break;
            default:
                value = 0;
                break;
        }
        
        toreturn['type'] = type;
        toreturn['altt'] = altt;
        toreturn['link'] = link; 

        return toreturn;
    }
    
    function constructChurchInfo(church)
    {
        var toreturn = '<div id="facebox_content">' +
				   '<div class="modalchurchimg"><img class="churchimg" src="' + baseURL + directory + '/themes/images/churchimg/churchpix.jpg" width="200" ></div>' +
				   '<div class="modalinfo">' +
				   '<h3><i>' + church.church_full_name + '</i></h3>' + 
				   '<label class="modalpastorname">' + church.pastor.full_name_with_title + '</label><br>' +
                   '<div class="labelmod">' + 
                       '<label class="modallabel">Founded:</label><br>' +
                       '<label class="modallabel">Address:</label><br>' + 
                       '<label class="modallabel">Landline:</label><br>' +
                       '<label class="modallabel">Website:</label><br>' + 					   
                   '</div>' + 
                   '<div class="labelmod1">' +
                       '<span class="modalvalue">' + church.founded + '</span><br>' + 
                       '<span class="modalvalue">' + church.address_display + '</span><br>' + 
                       '<span class="modalvalue">' + church.address.address_contact_number + '</span><br>' + 
                       '<span class="modalvalue">' + church.church_website + '</span><br>' + 
				   '</div>' +
				   '<div class="modalsmallinfo">' +
				       '<span class="modalvalue1">~ '+ church.church_number_of_members +'</span><br>' +
				       '<label class="modallabel1">Members</label>' +
				   '</div>' + 
				   '<div class="modalsmallinfo">' +
				       '<span class="modalvalue1">' + church.section.section_name + '</span><br>' +
				       '<label class="modallabel1">Section</label>' +
				   '</div>';
        
        if (church.social.length)
		{
		  toreturn +=	'<div class="modalsmallinfo">';
		}		   
        for (var i = 0; i < church.social.length; i++)
        {
            var social_info = getSocialInfo(church.social[i].social_type_id, church.social[i].social_link);
            
            toreturn += '<a class="tiptip" href="' + social_info['link'] + '" title="' + social_info['altt'] + '"><img class="smalliconmodal" rel="clickable" id="icon_disabled" src="' + baseURL + directory + '/themes/images/socialsmall/' + social_info['type'] + '.png" border="0"></a>';
        }
        
        if (church.social.length)
        {
            toreturn += '<br><label class="modallabel1">Social</label>';
        }
        toreturn += '</div></div></div>';
        
        return toreturn;
    }
    function constructPastorInfo(pastor)
    {
        return '<div id="facebox_content1">' +
 				   '<div class="modalchurchimg"><img class="churchimg" src="' + baseURL + directory + '/themes/images/churchimg/pastoricon.png" width="150"></div>' +
				   '<div class="modalinfo">' +
				   '<h3><i>' + pastor.full_name_with_title + '</i></h3>' + 
				   '<label class="modalpastorname"> '+ pastor.church.church_full_name +' </label><br>' +
                   '<div class="labelmod">' + 
                       '<label class="modallabel">Address:</label><br>' +
                       '<label class="modallabel">E-mail:</label><br>' +
                       '<label class="modallabel">Mobile:</label><br>' + 					   
                   '</div>' + 
                   '<div class="labelmod1">' +
                       '<span class="modalvalue">' + pastor.church.address_display + '</span><br>' + 
                       '<span class="modalvalue">' + pastor.user.user_email + '</span><br>' + 
                       '<span class="modalvalue"> 0900-123-4567 </span><br>' + 
				   '</div>' +
				   '<div class="modalsmallinfo">' +
				       '<span class="modalvalue1"> Where is my icon? </span><br>' +
				       '<label class="modallabel1">Social</label>' +
			   '</div>';
    }
    
    function updateSearchResult()
    {
        $.facebox('Loading contents');
        
        var url = baseURL + directory + '/church-locator/update-search-result';
        
        var values = { 
            state_id : $("#province").val(), 
            city_id  : $("#city").val(), 
            query    : $("#query").val()
        };
        
        // remove markers on map
        for (i in markersmap)
        {
            markersmap[i].setMap(null);
        }
        
        markersmap = [];
        htmlsmap   = [];
        churchinfo = [];
        pastorinfo = [];
        
        $.ajax(
        {
            type: "POST",
            url: url,
            data: values,
            success: function (data)
            {
                var churches = jQuery.parseJSON( data );
                var church;
                var pastor;
                
                var rowIdx;
                var churchItem;
                var point;
                var html;
                var marker;
                
                $("#churchsearch").html("");
                for( i = 0; i < churches.length; i++ )
                {
                    rowIdx = ( ( i+1 ) % 2 ) + 1; // for alternating rows
                    
                    church = churches[i].church_obj;
                    pastor = churches[i].pastor_obj;
                    social = churches[i].social_obj;
                    pastor.full_name_with_title = churches[i].pastor;
                    church.pastor = pastor;
                    church.social = social;
                    church.founded = churches[i].founded;
                    church.address_display = churches[i].address;
                    
                    pastor.church = church;
                    
                    point = new google.maps.LatLng(church.address.address_lat, church.address.address_lng);
                    
                    html = '<div style="text-align: left;"><strong>' + church.church_full_name + '</strong><br />' + church.address_display + '</div>';
                    marker = createMarker( churchmap, point, "", html, "sidebar_map", '' );
                    
                    htmlsmap.push(html);
                    markersmap.push(marker);
                    
                    churchinfo.push(constructChurchInfo(church));
                    pastorinfo.push(constructPastorInfo(pastor));
                                        
                    churchItem = 
                    '<div class="tablerow' + rowIdx + '">' + 
                        '<div class="searchedchurch"><a href="#modal" rel="church_full_name" id="' + i + '">' + church.church_full_name + '</a></div>' +
                        '<div class="searchedchurch1"><a href="#modal" rel="pastor" id="' + i + '">' + pastor.full_name_with_title + '</a></div>' +
                        '<div class="searchedchurch2">' + church.address.address_contact_number + '</div>' +
                        '<div class="map_marker" id="' + i + '">' + 
                            '<a href="#show">' +
                                '<img src="' + baseURL + directory + '/themes/images/map/map_pin.png" class="tiptip" title="Show location of ' + church.church_full_name + ' on map." alt="home" border="0"/>' +
                            '</a>' +
                        '</div>' +
                    '</div>';
                    
                    $("#churchsearch").append(churchItem);
                }
                
                // Tiptip
                $(function(){
                    $(".tiptip").tipTip();
                });
                
                // Modal for church information
                $('a[rel*=church_full_name]').click(function()
                {
                    $.facebox(churchinfo[this.id]);
                    
                    $("img[rel*=clickable]").mouseover(function(){
                        this.id = '';
                    });
                    
                    $("img[rel*=clickable]").mouseout(function(){
                        this.id = 'icon_disabled';
                    });
                    
                    $(function(){
                        $(".tiptip").tipTip();
                    });
                });
                
                // Modal for pastor information
                $('a[rel*=pastor]').click(function()
                {
                    $.facebox(pastorinfo[this.id]);
                });
                
                $("div.map_marker").click(function()
                {
                    scrollToMarker(this.id);
                });
                
                $(document).trigger('close.facebox');
                
                
            }
        });
        
        
    }
    
    $("#province").change( updateCityValues );
    $("#city").change( updateSearchResult );
    $("#searchchurch").click( updateSearchResult );
    
    $("#query").keypress(function(event)
    {
        if ( event.which == 13 )
        {
            updateSearchResult();
        }
    });
    
    updateSearchResult();

});